Zeabur AI Hub: すべてのAIモデル向け統合APIゲートウェイ

1. Zeabur AI Hubとは?

Zeabur AI Hubは、Claude、GPT、Gemini、DeepSeekなど、複数の主要AIモデルに単一のAPIでアクセスできる統合AIモデルアクセスプラットフォームです。異なるプロバイダーごとにAPIキーとアカウントを管理する代わりに、1つのAPIキーで標準化されたOpenAI互換インターフェースを通じてすべてのモデルにアクセスできます。

Zeabur AI Hub

主な機能

  • 統合API: すべてのモデル用の単一APIキー(Claude、GPT、Gemini、DeepSeek、Llamaなど)
  • OpenAI互換: 既存のOpenAI SDKコードで動作 - 学習コストなし
  • グローバルエンドポイント: 最適なレイテンシのための複数のリージョンエンドポイント
  • 競争力のある価格: 従量課制で透明な価格設定
  • 高度な機能: 関数呼び出し、構造化出力、ストリーミング、ビジョンなど
  • モデルの柔軟性: 1つのパラメータを変更するだけで即座にモデルを切り替え

前提条件

開始する前に、以下が必要です:

  1. Zeabur AI Hub APIキー(zeabur.com/ai-hubから取得)
  2. Python 3.7+のインストール
  3. PythonとAPI使用の基礎知識

始めましょう! 🚀

2. セットアップとインストール

まず、必要なパッケージをインストールし、環境変数を設定します。

# Install required packages
!pip install openai python-dotenv requests pillow -q

プロジェクトディレクトリに以下の形式で.envファイルを作成します:

ZEABUR_API_KEY=sk-your-api-key-here
import os
from dotenv import load_dotenv
from openai import OpenAI
import json

# Load environment variables from .env file
load_dotenv()

# Get API key from environment
ZEABUR_API_KEY = os.getenv("ZEABUR_API_KEY")

if not ZEABUR_API_KEY:
    raise ValueError("ZEABUR_API_KEY not found in .env file")

# Available endpoints
ENDPOINTS = {
    "tokyo": "https://hnd1.aihub.zeabur.ai/",
    "san_francisco": "https://sfo1.aihub.zeabur.ai/"
}

# Initialize client (using Tokyo endpoint by default)
client = OpenAI(
    base_url=ENDPOINTS["tokyo"],
    api_key=ZEABUR_API_KEY
)

print("✅ Setup complete! Client initialized with Tokyo endpoint.")
✅ Setup complete! Client initialized with Tokyo endpoint.

3. 基本的なチャット補完

Zeabur AI Hubは複数のモデルをサポートしています。利用可能なモデルは以下の通りです:

Claudeモデル:

  • claude-sonnet-4-5: 高度な推論と分析
  • claude-haiku-4-5: 高速で効率的な応答

GPTモデル:

  • gpt-5: 最新のOpenAIモデル
  • gpt-5-mini: より小さく高速なバージョン
  • gpt-4.1, gpt-4.1-mini: 前世代
  • gpt-4o, gpt-4o-mini: 最適化されたバリアント

Geminiモデル:

  • gemini-2.5-pro, gemini-2.5-flash: Googleのマルチモーダルモデル

その他のモデル:

  • deepseek-v3.2-exp: DeepSeekの効率的なモデル
  • llama-3.3-70b: Metaのオープンソースモデル
  • qwen-3-32: Alibabaの推論モデル
  • kimi-k2-thinking: Moonshot AIの推論モデル
# Basic non-streaming completion
def simple_chat(model="claude-haiku-4-5", message="Hello! Tell me about AI in 20 words."):
    """Send a simple chat message and get a complete response."""
    response = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": message}],
        max_tokens=500
    )
    return response.choices[0].message.content

# Test with Claude Haiku
print("Using Claude Haiku 4.5:")
print("-" * 50)
result = simple_chat(model="claude-haiku-4-5")
print(result)
print("\n")

# Test with GPT-4o
print("Using GPT-4o:")
print("-" * 50)
result = simple_chat(model="gpt-4o")
print(result)
Using Claude Haiku 4.5:
--------------------------------------------------
AI enables machines to learn from data and perform tasks intelligently, mimicking human cognition through algorithms and neural networks.


Using GPT-4o:
--------------------------------------------------
AI, or Artificial Intelligence, is the development of computer systems to perform tasks requiring human-like intelligence, such as learning, reasoning, and problem-solving.

4. ストリーミング応答

ストリーミングにより、AIの応答をトークンごとに生成されると同時に受信でき、インタラクティブなアプリケーションのユーザー体験を向上させます。

def streaming_chat(model="claude-haiku-4-5", message="Tell me a short story about a robot in 30 words."):
    """Stream chat responses token by token."""
    stream = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": message}],
        stream=True,
        max_tokens=300
    )
    
    print(f"Streaming response from {model}:")
    print("-" * 50)
    
    full_response = ""
    for chunk in stream:
        content = chunk.choices[0].delta.content or ''
        if content:
            print(content, end='', flush=True)
            full_response += content
    
    print("\n" + "-" * 50)
    return full_response

# Test streaming
response = streaming_chat(
    model="claude-sonnet-4-5"
)

# Test streaming
response = streaming_chat(
    model="gpt-4o"
)
Streaming response from claude-sonnet-4-5:
--------------------------------------------------
The lonely robot tended Earth's last garden for centuries after humans left. One day, a seedling sprouted. "Welcome," it whispered to the tiny plant, "I'm not alone anymore."
--------------------------------------------------
Streaming response from gpt-4o:
--------------------------------------------------
A lonely robot discovered a flower in the wasteland. Carefully, it nurtured it, learning love. When the flower bloomed, the robot felt alive, no longer just a machine.
--------------------------------------------------

5. モデルの比較と選択

異なるモデルには異なる強みがあります。複数のプロバイダー間でモデルを比較し、パフォーマンスと応答品質を確認しましょう。

比較の主な機能:

  • プロバイダーマッピング: モデル接頭辞でプロバイダーを識別するクリーンな辞書を使用
  • 思考タグの削除: 推論モデルから<think>と<thinking>タグを自動的に削除
  • パフォーマンス指標: 各モデルの応答時間とトークン使用量を追跡
  • エラーハンドリング: モデルエラーや非互換性を適切に処理

7つの異なるプロバイダーから7つのモデルをテストします:Anthropic、OpenAI、xAI、DeepSeek、Meta、Alibaba、Moonshot AI。

import time
import re

# Provider mapping
PROVIDERS = {
    "claude": "Anthropic",
    "gpt": "OpenAI",
    "gemini": "Google",
    "grok": "xAI",
    "deepseek": "DeepSeek",
    "llama": "Meta",
    "qwen": "Alibaba",
    "kimi": "Moonshot AI"
}

def get_provider_name(model):
    """Get provider name based on model prefix."""
    for prefix, provider in PROVIDERS.items():
        if model.startswith(prefix):
            return provider
    return "Unknown"

def clean_response(content):
    """Remove thinking tags from model responses."""
    if not content:
        return content
    
    original = content
    
    # Remove thinking content for tags: <think>, <thinking>
    for tag in ['think', 'thinking']:
        # Extract content after closing tag if it exists
        closing = f'</{tag}>'
        if closing in content.lower():
            parts = re.split(closing, content, flags=re.IGNORECASE | re.DOTALL)
            content = parts[-1].strip()
        
        # Remove from opening tag onwards if no closing tag
        opening = f'<{tag}>'
        if opening in content.lower():
            content = re.split(opening, content, flags=re.IGNORECASE | re.DOTALL)[0].strip()
    
    return content if content.strip() else original

def compare_models(prompt, models, max_tokens_map=None):
    """Compare response quality and speed across different models."""
    max_tokens_map = max_tokens_map or {}
    results = []
    
    for model in models:
        print(f"Testing {model}...")
        start_time = time.time()
        
        try:
            response = client.chat.completions.create(
                model=model,
                messages=[{"role": "user", "content": prompt}],
                max_tokens=max_tokens_map.get(model, 200)
            )
            
            content = clean_response(response.choices[0].message.content)
            
            results.append({
                "model": model,
                "provider": get_provider_name(model),
                "response": content or "[Empty response]",
                "time_seconds": round(time.time() - start_time, 2),
                "tokens": getattr(response.usage, 'total_tokens', "N/A")
            })
            
        except Exception as e:
            results.append({
                "model": model,
                "provider": get_provider_name(model),
                "response": f"Error: {str(e)[:100]}",
                "time_seconds": 0,
                "tokens": 0
            })
    
    return results

# Test configuration
test_prompt = "Tell me a joke in 20 words."

models_to_test = [
    "claude-haiku-4-5",
    "gpt-4o-mini",
    "grok-4-fast-non-reasoning",
    "deepseek-v3.2-exp",
    "llama-3.3-70b",
    "qwen-3-32",
    "kimi-k2-thinking"
]

# Thinking models need more tokens
max_tokens_map = {
    "kimi-k2-thinking": 800,
    "qwen-3-32": 800,
}

# Run comparison
print("Comparing Models Across Providers")
print("=" * 80)
print(f"Prompt: {test_prompt}\n")

results = compare_models(test_prompt, models_to_test, max_tokens_map)

# Display results
for r in results:
    print(f"\n{'=' * 80}")
    print(f"Provider: {r['provider']} | Model: {r['model']}")
    print(f"Time: {r['time_seconds']}s | Tokens: {r['tokens']}")
    print(f"Response: {r['response'][:500]}")

# Summary
print(f"\n{'=' * 80}")
print("SUMMARY")
print("=" * 80)

successful = [r for r in results if not r['response'].startswith('Error') and not r['response'].startswith('[')]

if successful:
    print(f"Successful: {len(successful)}/{len(results)}")
    print(f"Average time: {sum(r['time_seconds'] for r in successful) / len(successful):.2f}s")
    
    fastest = min(successful, key=lambda x: x['time_seconds'])
    slowest = max(successful, key=lambda x: x['time_seconds'])
    
    print(f"Fastest: {fastest['model']} ({fastest['provider']}) - {fastest['time_seconds']}s")
    print(f"Slowest: {slowest['model']} ({slowest['provider']}) - {slowest['time_seconds']}s")
    
    # Provider breakdown
    print(f"\nProviders tested:")
    providers = sorted(set(r['provider'] for r in successful))
    for provider in providers:
        provider_models = [r['model'] for r in successful if r['provider'] == provider]
        print(f"  - {provider}: {', '.join(provider_models)}")
else:
    print("No successful tests.")
Comparing Models Across Providers
================================================================================
Prompt: Tell me a joke in 20 words.

Testing claude-haiku-4-5...
Testing gpt-4o-mini...
Testing grok-4-fast-non-reasoning...
Testing deepseek-v3.2-exp...
Testing llama-3.3-70b...
Testing qwen-3-32...
Testing kimi-k2-thinking...

================================================================================
Provider: Anthropic | Model: claude-haiku-4-5
Time: 1.31s | Tokens: 38
Response: Why did the scarecrow win an award? Because he was outstanding in his field!

================================================================================
Provider: OpenAI | Model: gpt-4o-mini
Time: 0.09s | Tokens: 42
Response: Why did the scarecrow win an award? Because he was outstanding in his field, keeping crows away while standing still!

================================================================================
Provider: xAI | Model: grok-4-fast-non-reasoning
Time: 0.49s | Tokens: 197
Response: Why did the scarecrow win an award? He was outstanding in his field! (9 words)

================================================================================
Provider: DeepSeek | Model: deepseek-v3.2-exp
Time: 0.11s | Tokens: 31
Response: Why did the chicken cross the playground? To get to the other slide.

================================================================================
Provider: Meta | Model: llama-3.3-70b
Time: 0.51s | Tokens: 65
Response: Why was the math book sad? Because it had too many problems to solve every single day always.

================================================================================
Provider: Alibaba | Model: qwen-3-32
Time: 0.62s | Tokens: 341
Response: 

"Why did the duck leave the pond? Too many quackers around, it said. Swam to a quieter lake." (20 words)

================================================================================
Provider: Moonshot AI | Model: kimi-k2-thinking
Time: 13.2s | Tokens: 791
Response:  A man walked into a library asking for a book on Pavlov's dogs. The librarian said, "It rings a bell."

================================================================================
SUMMARY
================================================================================
Successful: 7/7
Average time: 2.33s
Fastest: gpt-4o-mini (OpenAI) - 0.09s
Slowest: kimi-k2-thinking (Moonshot AI) - 13.2s

Providers tested:
  - Alibaba: qwen-3-32
  - Anthropic: claude-haiku-4-5
  - DeepSeek: deepseek-v3.2-exp
  - Meta: llama-3.3-70b
  - Moonshot AI: kimi-k2-thinking
  - OpenAI: gpt-4o-mini
  - xAI: grok-4-fast-non-reasoning

まとめと次のステップ

Zeabur AI Hubの重要な概念を学びました:

  1. セットアップ: .envからAPIキーを読み込み、OpenAI互換クライアントを初期化
  2. 基本的な補完: 異なるモデルで簡単なチャットリクエストを行う
  3. ストリーミング: より良いUXのためのリアルタイムトークン単位の応答を受信
  4. モデル比較: 自動パフォーマンス追跡と思考タグ削除で複数のプロバイダーをテスト

重要なポイント:

  • Zeabur AI Hubは7以上のAIプロバイダー向けの統合APIを提供
  • 1つのパラメータを変更するだけでモデルを切り替え可能 - コード変更は不要
  • 推論モデル(Qwen、Kimi)は<think>タグを使用し、自動的にフィルタリング可能
  • パフォーマンスは大きく異なる:GPT-4o-miniが最速(0.09秒)、Kimi-k2が最遅(13.2秒)

🎁 ベータテスタープロモーション

Zeabur AI Hubはベータ版です! 今登録すると、招待コードを使用して10ドルのクレジットを取得できます。各テスターは3つの招待コードを共有でき、3人の友人を招待するとさらに10ドルのクレジットを獲得!

招待コードを取得: Discord、Twitter/X、またはThreadsで@zeaburappに言及してコードを請求しましょう!

追加リソース